package middleware

import (
	"encoding/gob"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type LoginMiddlewareBuilder struct {
}

func NewLoginMiddlewareBuilder() *LoginMiddlewareBuilder {
	return &LoginMiddlewareBuilder{}
}
func (l *LoginMiddlewareBuilder) Build() gin.HandlerFunc {
	gob.Register(time.Now())
	return func(context *gin.Context) {
		//不需要登录校验的
		if context.Request.URL.Path == "/users/login" || context.Request.URL.Path == "/user/signup" {
			return
		}
		sess := sessions.Default(context)
		//if sess == nil {
		//	//没有登录
		//	context.AbortWithStatus(http.StatusUnauthorized)
		//	return
		//}
		id := sess.Get("userId")
		if id == nil {
			//没有登录
			context.AbortWithStatus(http.StatusUnauthorized)
			return
		}

		updateTime := sess.Get("update_time")
		sess.Set("userId", id)
		now := time.Now()
		//说明还没有刷新过，刚登陆，还没刷新
		if updateTime == nil {
			sess.Set("update_time", now)
			sess.Options(sessions.Options{
				MaxAge: 60,
			})
			sess.Save()
			return
		}
		//updateTime有
		updateTimeVal, _ := updateTime.(time.Time)

		if now.Sub(updateTimeVal) > time.Second*10 {
			sess.Set("update_time", now)
			sess.Save()
			return
		}

	}
}
